﻿using Microsoft.Extensions.Logging;
using MQTTnet.Client.Publishing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PHMEE.MqttClient
{
    public abstract class BaseCommand
    {
        /// <summary>
        /// 是否需要回复
        /// </summary>
        public bool isReplay { set; get; } = false;
        /// <summary>
        /// 采集器SN
        /// </summary>
        public string SN { set; get; }
        /// <summary>
        /// 消息id
        /// </summary>
        public string? MessageId { set; get; }
        /// <summary>
        /// 日志对象
        /// </summary>
        public ILogger _logger { get; set; }
        /// <summary>
        /// 回复内容
        /// </summary>
        public object ResPonsePayload { set; get; } = null;
        /// <summary>
        /// 处理状态
        /// </summary>
        public int Status { set; get; } = 1;
        /// <summary>
        /// 处理状态
        /// </summary>
        public string RequestTopic { set; get; } = "";

        /// <summary>
        /// 返回指令名称，默认去掉 "Command" 后缀
        /// </summary>
        public virtual string CommandName
        {
            get
            {
                var name = GetType().Name;
                return name.EndsWith("Command") ? name.Substring(0, name.Length - "Command".Length) : name;
            }
        }

        public void SetLogger(ILogger logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 回复主题
        /// </summary>
        public string ResPonseTopic
        {
            get
            {
                return $"{SN}/{CommandName}/{MessageId}/{Status}";
            }
        }
        //消息处理逻辑
        public abstract Task ExecuteAsync(string requestInfo);
        //回复数据代理
        public required Func<string, string, Task<MqttClientPublishResult>> ReplyAsyncDelegacy;
        /// <summary>
        /// Mqtt客户端id
        /// </summary>
        public string? ClientId { set; get; }

        /// <summary>
        /// 各个指令返回值
        /// </summary>
        public object? ReturnData { set; get; }
        //回复数据
        public async Task<bool> ReplyAsync()
        {
            isReplay = false;
            string ResPonseString = "";
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-ddTHH:mm:ss"
            };
            if (ResPonsePayload != null)
                ResPonseString = JsonConvert.SerializeObject(ResPonsePayload, timeFormat);
            Console.WriteLine($"\n ============={CommandName}回复的负载【{ResPonseString}】=============\n");
            // 构造完整的主题
            MqttClientPublishResult mqttResult = await ReplyAsyncDelegacy(ResPonseTopic, ResPonseString);
            if (mqttResult.ReasonCode != MqttClientPublishReasonCode.Success)
            {
                _logger.LogError($"SN:{SN} with topic {ResPonseTopic} send response fail,with ReasonCode {mqttResult.ReasonCode} and reason {mqttResult.ReasonString} ");
                return false;
            }
            return true;
        }
    }
}
